package com.oscroll.delegate.lesson.servlet;

import com.oscroll.delegate.lesson.servlet.controller.MemberAction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class ServletDispatcher {

    private List<Handler> handlerMapping = new ArrayList<Handler>();

    public ServletDispatcher() {
        try {
            Class<?> memberActionClass = MemberAction.class;
            handlerMapping.add(new Handler().setController(memberActionClass).setMethod(memberActionClass.getMethod("getMemberById", String.class)).setUrl("aa"));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public void doService(HttpServletRequest request, HttpServletResponse response) {
        doDispatcher(request, response);
    }

    public void doDispatcher(HttpServletRequest request, HttpServletResponse response) {
        // 1、获取用户url请求
        String uri = request.getRequestURI();
        // 2、servlet拿到url以后，要做权衡

        // 3、通过拿到的URL去handlerMapping
        Handler handler = null;
        for (Handler h : handlerMapping) {
            if (uri.equals(h.getUrl())) {
                handler = h;
                break;
            }
        }

        // 4、通过反射去调用其对应的方法--将具体任务分发给method
        Object object = null;
        try {
            handler.getMethod().invoke(handler.getController(), request.getParameter("mid"));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 5、获取Method执行的结果，通过response返回出去
        try {
            response.getWriter().print(object);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class Handler {
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public Handler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public Handler setMethod(Method method) {
            this.method = method;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public Handler setUrl(String url) {
            this.url = url;
            return this;
        }
    }
}
